# monitor_config.py
import sqlite3
import json
from pathlib import Path

from PySide6.QtCore import QUrl
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import QDialog, QVBoxLayout, QLabel, QPushButton, QMessageBox, QComboBox, QLineEdit, QHBoxLayout


class MonitorConfig:
    DB_PATH = "device_config/config_file/device_info.db"

    def __init__(self, parent):
        self.parent = parent
        self.config_data = {}
        self.init_database()

    def get_db_connection(self):
        """创建数据库连接"""
        return sqlite3.connect(self.DB_PATH, timeout=20)

    def init_database(self):
        """初始化数据库和devices_regex表"""
        try:
            with self.get_db_connection() as conn:
                cursor = conn.cursor()
                cursor.execute('''
                    CREATE TABLE IF NOT EXISTS devices_regex (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        vendor TEXT NOT NULL,
                        command TEXT NOT NULL,
                        command_content TEXT NOT NULL,
                        regex TEXT NOT NULL,
                        UNIQUE(vendor, command)
                    )
                ''')
                
                # 检查表是否为空
                cursor.execute("SELECT COUNT(*) FROM devices_regex")
                if cursor.fetchone()[0] == 0:
                    self.migrate_json_to_db()
                conn.commit()
        except Exception as e:
            self.parent.show_message(f"初始化数据库失败: {e}")

    def migrate_json_to_db(self):
        """将JSON配置文件数据迁移到数据库"""
        json_path = "device_config/config_file/device_info_config.json"
        if not Path(json_path).exists():
            return
            
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
            
            with self.get_db_connection() as conn:
                cursor = conn.cursor()
                for vendor in config["command_mapping"]:
                    for command, command_content in config["command_mapping"][vendor].items():
                        regex = config["regex_mapping"].get(vendor, {}).get(command, "")
                        cursor.execute(
                            "INSERT INTO devices_regex (vendor, command, command_content, regex) VALUES (?, ?, ?, ?)",
                            (vendor, command, command_content, regex)
                        )
                conn.commit()
        except Exception as e:
            self.parent.show_message(f"迁移数据失败: {e}")

    def load_config_data(self):
        """从数据库加载配置"""
        try:
            with self.get_db_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT vendor, command, command_content, regex FROM devices_regex")
                rows = cursor.fetchall()
                
                self.config_data = {"command_mapping": {}, "regex_mapping": {}}
                
                for row in rows:
                    vendor, command, command_content, regex = row
                    
                    if vendor not in self.config_data["command_mapping"]:
                        self.config_data["command_mapping"][vendor] = {}
                    if vendor not in self.config_data["regex_mapping"]:
                        self.config_data["regex_mapping"][vendor] = {}
                    
                    self.config_data["command_mapping"][vendor][command] = command_content
                    self.config_data["regex_mapping"][vendor][command] = regex
        except Exception as e:
            self.parent.show_message(f"加载配置失败: {e}")

    def save_all_mappings(self, config_data):
        """保存配置到数据库"""
        vendor = self.command_mapping_combo.currentText()
        command = self.command_combo.currentText()
        regex = self.regex_input.text()
        command_content = self.command_lines[command].text()

        if vendor and command and regex:
            try:
                with self.get_db_connection() as conn:
                    cursor = conn.cursor()
                    cursor.execute("""
                        INSERT OR REPLACE INTO devices_regex (vendor, command, command_content, regex)
                        VALUES (?, ?, ?, ?)
                    """, (vendor, command, command_content, regex))
                    conn.commit()
                
                self.load_config_data()
                QMessageBox.information(self.parent, "成功", f"{vendor} 的命令和正则均已更新")
            except Exception as e:
                QMessageBox.warning(self.parent, "错误", f"保存配置失败: {e}")
        else:
            QMessageBox.warning(self.parent, "警告", "请确保所有字段都已选择并填写")

    def edit_monitor_config(self):
        try:
            # 创建对话框
            dialog = QDialog(self.parent)
            dialog.setFixedWidth(300)
            dialog.setWindowTitle("编辑命令和正则映射")
            layout = QVBoxLayout(dialog)
            layout.addWidget(QLabel("1、选择厂商，刷新命令列表\n2、选择命令，刷新正则表达式\n3、在正则表达式中填入需要匹配的字符\n4、重启软件以使更改生效"))

            open_link_button = QPushButton("正则表达式生成器-需联网：https://regex.ai/")
            open_link_button.clicked.connect(lambda: QDesktopServices.openUrl(QUrl("https://regex.ai/")))
            layout.addWidget(open_link_button)

            # 加载配置数据
            self.load_config_data()

            # 处理命令映射
            self.command_mapping_combo = QComboBox()
            vendors = list(self.config_data["command_mapping"].keys())
            self.command_mapping_combo.addItems(vendors)

            layout.addWidget(QLabel("1、选择厂商:"))
            self.command_mapping_combo.currentIndexChanged.connect(
                lambda: self.load_commands(self.command_mapping_combo.currentText())
            )
            layout.addWidget(self.command_mapping_combo)

            # 选择的交互式布局
            self.command_layout = QVBoxLayout()
            layout.addLayout(self.command_layout)

            # 选择命令的下拉框
            self.command_combo = QComboBox()
            layout.addWidget(QLabel("2、选择命令:"))
            layout.addWidget(self.command_combo)

            self.regex_input = QLineEdit()
            layout.addWidget(QLabel("正则表达式:"))
            layout.addWidget(self.regex_input)

            # 添加按钮以保存更改
            button_layout = QHBoxLayout()
            save_button = QPushButton("保存")
            save_button.clicked.connect(lambda: self.save_all_mappings(self.config_data))
            button_layout.addWidget(save_button)

            cancel_button = QPushButton("取消")
            cancel_button.clicked.connect(dialog.close)
            button_layout.addWidget(cancel_button)

            layout.addLayout(button_layout)

            # 初始加载第一个厂商的命令
            if vendors:
                self.load_commands(vendors[0])

            dialog.exec()

        except Exception as e:
            self.parent.show_message(f"编辑配置时出错: {e}")

    def load_commands(self, vendor):
        """从数据库加载指定厂商的命令"""
        if not vendor:
            return

        self.command_combo.clear()
        self.command_lines = {}

        for i in reversed(range(self.command_layout.count())):
            widget = self.command_layout.itemAt(i).widget()
            if widget is not None:
                widget.deleteLater()

        try:
            with self.get_db_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("""
                    SELECT command, command_content 
                    FROM devices_regex 
                    WHERE vendor = ?
                """, (vendor,))
                
                commands = cursor.fetchall()
                
                for command, command_content in commands:
                    command_line = QLineEdit(command_content)
                    self.command_lines[command] = command_line

                    label = QLabel(f"{command}:")
                    self.command_layout.addWidget(label)
                    self.command_layout.addWidget(command_line)
                    
                    self.command_combo.addItem(command)
            
            self.command_combo.currentIndexChanged.connect(
                lambda: self.load_regex(vendor)
            )
            self.regex_input.clear()
            
            if commands:
                self.load_regex(vendor)
                
        except Exception as e:
            self.parent.show_message(f"加载命令失败: {e}")

    def load_regex(self, vendor):
        """从数据库加载指定厂商和命令的正则表达式"""
        command = self.command_combo.currentText()
        if not command:
            return
        
        try:
            with self.get_db_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("""
                    SELECT regex 
                    FROM devices_regex 
                    WHERE vendor = ? AND command = ?
                """, (vendor, command))
                
                result = cursor.fetchone()
                if result:
                    self.regex_input.setText(result[0])
                else:
                    self.regex_input.clear()
        except Exception as e:
            self.parent.show_message(f"加载正则表达式失败: {e}")


